//
//  MCompletedTaskViewController.m
//  Gunz
//
//  Created by Joggy on 16/5/4.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "MCompletedTaskViewController.h"
#import "MJRefresh.h"
#import "GZConst.h"
#import "MCompletedViewCell.h"
#import "GZLoginState.h"
#import "CoreStatus.h"
#import "QYNotice.h"
#import "GZNetRequest.h"
#import "UIImageView+WebCache.h"
#import "TaskDetailViewController.h"
#import "MAssessViewController.h"

@interface MCompletedTaskViewController ()<UITableViewDelegate, UITableViewDataSource> {
    
    UITableView *table;
    NSArray* data;
    
}

@end

@implementation MCompletedTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareForNav];
    [self prepareForLayout];
}

- (void)prepareForNav {
    [super prepareForNav];
    self.title = @"已完成的任务";
    //导航左按键
    UIImage *image = [UIImage imageNamed:@"all_back"];
    UIButton *leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBarButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    leftBarButton.layer.position = CGPointMake(22, 22);
    [leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [leftBarButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarButton];
}

- (void)prepareForLayout {
    [super prepareForLayout];
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64)];
    table.delegate = self;
    table.dataSource = self;
    table.backgroundColor = [UIColor clearColor];
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [table registerClass:[MCompletedViewCell class] forCellReuseIdentifier:@"MCompletedCell"];
    table.showsVerticalScrollIndicator = false;
    table.showsHorizontalScrollIndicator = false;
    table.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [table.mj_header beginRefreshing];
    [self.view addSubview:table];
}

- (void)headerRefresh {
    if([CoreStatus isNetworkEnable]) {
        NSString *url = @"http://180.209.64.49:8001/task/getFinshedListById";
        NSDictionary *para = @{@"uid": [GZLoginState getCurrentLoginUserID], @"lastid": @"0"};
        NSLog(@"%@", para);
        [[GZNetRequest getPOSTManager] POST:url parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
            
            NSDictionary *dic = responseObject;
            if([dic[@"state"] isEqualToString:@"success"]) {
                NSArray *arr = dic[@"msg"];
                data = arr;
                if(data.count <= 0) {
                    data = [GZConst defaultExcutingData];
                }
                [table reloadData];
            }
            else {
                [QYNotice showError:@"获取失败" toView:self.view];
                [QYNotice dismissWithDelay:3];
            }
            [table.mj_header endRefreshing];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
            [QYNotice showError:@"获取失败" toView:self.view];
            [QYNotice dismissWithDelay:3];
            data = [GZConst defaultExcutingData];
            [table reloadData];
            [table.mj_header endRefreshing];
        }];
    }
    else {
        [QYNotice showWarning:@"未检测到网络" toView:self.view];
        [QYNotice dismissWithDelay:3];
        [table.mj_header endRefreshing];
    }
}

//评价方法
- (void)assess:(UIButton*)button {
    MAssessViewController *assess = [[MAssessViewController alloc] init];
    assess.assessToTaskId = button.tag;
    [self.navigationController pushViewController:assess animated:true];
}

- (void)back {
    [self.navigationController popViewControllerAnimated:true];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma 代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    NSDictionary *tep = data[indexPath.section];
    if([tep[@"icontask"] isEqualToString:@"__no"]) {
        TaskDetailViewController *detail = [[TaskDetailViewController alloc] init];
        detail.isMineRelease = false;
        detail.hidesBottomBarWhenPushed = true;
        detail.data = tep[@"fields"];
        detail.isBarButtonHidden = true;
        [self.navigationController pushViewController:detail animated:true];
    }
    else {
//        NSDictionary *para = @{@"id": tep[@"id"], @"parenttask_id": tep[@"parenttask_id"]};
        NSDictionary *para = @{@"id": tep[@"id"]};
        [[GZNetRequest getPOSTManager] POST:@"http://180.209.64.49:8001/task/taskDetail" parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic1 = responseObject;
            NSArray *arr1 = dic1[@"msg"];
            NSDictionary *dic2 = arr1[0];
            NSDictionary *dic3 = dic2[@"fields"];
            NSLog(@"%@", dic3);
            TaskDetailViewController *detail = [[TaskDetailViewController alloc] init];
            detail.isMineRelease = false;
            detail.hidesBottomBarWhenPushed = true;
            detail.data = dic3;
            detail.isBarButtonHidden = true;
            [self.navigationController pushViewController:detail animated:true];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //        NSLog(@"%@", error);
            
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return data.count;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, MineVCInsert)];
    headView.backgroundColor = [UIColor clearColor];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return MineVCInsert;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return MineVCCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MCompletedViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MCompletedCell"];
    
    NSDictionary *tep = data[indexPath.section];
    NSString *imgURL = @"http://180.209.64.49:8001/";
    imgURL = [imgURL stringByAppendingString:tep[@"icontask"]];
    [cell.headImage sd_setImageWithURL:[NSURL URLWithString:imgURL] placeholderImage:[UIImage imageNamed:@"插图1"]];
    cell.headTitle.text = tep[@"name"];
    cell.beginTime.text = tep[@"jointime"];
    cell.endTime.text = tep[@"jointime"];
    [cell.statusButton addTarget:self action:@selector(assess:) forControlEvents:UIControlEventTouchUpInside];
    cell.statusButton.tag = [tep[@"id"] integerValue];
    
    return cell;
}

@end
